import { NextRequest, NextResponse } from 'next/server'
import { createServerClient } from '@supabase/ssr'
import { join } from 'path'
import { deleteTool, updateTool, getTools } from '@/lib/database'
import { requireAdmin, withErrorHandling } from '@/lib/auth-middleware'

// 更新工具信息
export const PATCH = withErrorHandling(async (request: NextRequest, context?: { params: Promise<{ id: string }> }) => {
  return requireAdmin(request, async (req) => {
    // 从URL中提取工具ID，因为context可能由于中间件而丢失
    const url = new URL(request.url)
    const id = url.pathname.split('/').pop()

    if (!id) {
      return NextResponse.json(
        { error: '缺少工具ID参数' },
        { status: 400 }
      )
    }

    const body = await request.json()
    const { title, description, url: toolUrl, categoryId, status } = body

    console.log(`管理员 ${req.user?.name} 更新工具 ${id}:`, { title, status })

    try {
      // 更新工具信息
      const updatedTool = await updateTool(id, {
        title,
        description,
        url: toolUrl,
        categoryId,
        status
      })

      return NextResponse.json({
        success: true,
        data: updatedTool,
        message: '工具信息更新成功'
      })
    } catch (error) {
      console.error('更新工具失败:', error)
      return NextResponse.json({
        success: false,
        error: '更新工具失败'
      }, { status: 500 })
    }
  })
})

export const DELETE = withErrorHandling(async (request: NextRequest, context?: { params: Promise<{ id: string }> }) => {
  return requireAdmin(request, async (req) => {
    // 从URL中提取工具ID，因为context可能由于中间件而丢失
    const url = new URL(request.url)
    const id = url.pathname.split('/').pop()
    
    if (!id) {
      return NextResponse.json(
        { error: '缺少工具ID参数' },
        { status: 400 }
      )
    }

    console.log(`管理员 ${req.user?.name} 删除工具: ${id}`)

    // 删除部署的文件
    const deployDir = join(process.cwd(), 'public', 'deployed-tools', id)

    try {
      await import('fs').then(fs => {
        if (fs.existsSync(deployDir)) {
          fs.rmSync(deployDir, { recursive: true })
        }
      })
    } catch (error) {
      console.error('删除部署文件失败:', error)
      // 继续执行，即使文件删除失败也不影响数据库操作
    }

    // 从数据库删除工具
    try {
      await deleteTool(id)
      
      return NextResponse.json({
        success: true,
        message: '工具删除成功'
      })
    } catch (error) {
      console.error('删除工具失败:', error)
      return NextResponse.json({
        success: false,
        error: '删除工具失败'
      }, { status: 500 })
    }
  })
})
